define(['./module'], function(basicusermodule) {
    'use strict';

    basicusermodule.controller('basicuser', serverBasicuser);
    function serverBasicuser($scope, $http, $location,Upload,$timeout) {

        $scope.$watch('rmainfiles', function () {
            $scope.uploadrmainfiles($scope.rmainfiles);
        });
        $scope.allrmainfiles = [];
        $scope.uploadrmainfiles = function (files) {
            if (files && files.length) {
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    var filename = files[i].name;
                    if (!file.$error) {
                        Upload.upload({
                            url: '../mall/files/ajaxFileUploadsImgs',
                            data: {
                                file: file,
                                filename: filename
                            }
                        }).progress(function (evt) {
                            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                            $scope.rmainprogress = progressPercentage;
                        }).success(function (data, status, headers, config) {
                            $timeout(function () {
                                if (data.ifb.sucflag) {
                                    $scope.allrmainfiles.push(data.ifb);
                                }
                            });
                        });
                    }
                }
            }
        }

        $scope.removeallrmainfiles = function (index) {
            $scope.allrmainfiles.splice(index, 1);
        }


        //通过location中的operate参数区分操作行为
        var operate = $location.search().operate;
        if (operate != undefined && operate == "save") {
            //控制保存按钮显示
            $scope.savebtn = {show: true};
            $scope.title = '添加系统会员';
            $scope.userstatus = "1";
            $scope.istemp = "1";
            //保存数据方法
            $scope.save = function() {

              var username=$scope.username;
              if(username==undefined){
                $scope.errors = {
                    show: true,
                    msg: "请输入登录用户名"
                }
                return false;
              }
            	var password = $scope.password;
            	if (password == undefined){
                $scope.errors = {
                    show: true,
                    msg: "请输入登录密码"
                }
                return false;
              }
              var email=$scope.email;
              if (email == undefined){
                $scope.errors = {
                    show: true,
                    msg: "请输入邮箱"
                }
                return false;
              }
              var mobile=$scope.mobile;
              if (mobile == undefined){
                $scope.errors = {
                    show: true,
                    msg: "请输入手机"
                }
                return false;
              }
              var mainimg=angular.toJson($scope.allrmainfiles);
                $http({
                    method: 'POST',
                    url: '../mall/basicuser/save',
                    data: {
                        'email':email,
                        'username':username,
                        'password':password,
                        'mobile':mobile,
                        'mainimg':mainimg,
                        'istemp':$scope.istemp,
                        'userstatus':$scope.userstatus
                    }
                }).success(function(data, status, headers, config) {
                    if (data.sucflag) {
                        $scope.info = {
                            show: true,
                            msg: '系统用户添加成功'
                        }
                        $location.path('/basicuserment');
                    }else{
                        $scope.errors = {
                            show: true,
                            msg: data.msg
                        }
                    }
                }).error(function(data, status, headers, config) {
                    $scope.errors = {
                        show: true,
                        msg: '系统异常'
                    }
                });

            }
        }

        //如果operate是edit则执行保存行为
        if (operate == 'edit') {
            var id = $location.search().id;
            if (id != undefined && id != "") {
                $http({
                    method: 'POST',
                    url: '../mall/basicuser/find',
                    data: {
                        'id': id
                    }
                }).success(function(data, status, headers, config) {
                    if (data.sucflag) {
                        $scope.title = '正在对系统用户进行编辑';
                        $scope.username = data.bean.username;
                        $scope.password = "******";
                        $scope.email = data.bean.email;
                        $scope.mobile = data.bean.mobile;
                        $scope.istemp = data.bean.istemp;
                        $scope.userstatus = data.bean.userstatus;
                        $scope.allrmainfiles.push(data.ifb);
                        $scope.updatebtn = {show: true};
                    }
                }).error(function(data, status, headers, config) {
                    $scope.errors = {
                        show: true,
                        msg: '系统异常'
                    }
                });
                //更新数据方法
                $scope.update = function() {
                    var username=$scope.username;
                    if(username==undefined){
                        $scope.errors = {
                            show: true,
                            msg: "请输入登录用户名"
                        }
                        return false;
                    }
                    var password = $scope.password;
                    if (password == undefined){
                        $scope.errors = {
                            show: true,
                            msg: "请输入登录密码"
                        }
                        return false;
                    }
                    var email=$scope.email;
                    if (email == undefined){
                        $scope.errors = {
                            show: true,
                            msg: "请输入邮箱"
                        }
                        return false;
                    }
                    var mobile=$scope.mobile;
                    if (mobile == undefined){
                        $scope.errors = {
                            show: true,
                            msg: "请输入手机"
                        }
                        return false;
                    }
                    var mainimg=angular.toJson($scope.allrmainfiles);
                    $http({
                        method: 'POST',
                        url: '../mall/basicuser/update',
                        data: {
                            'id':id,
                            'email':email,
                            'mobile':mobile,
                            'mainimg':mainimg,
                            'istemp':$scope.istemp,
                            'userstatus':$scope.userstatus
                        }
                    }).success(function(data, status, headers, config) {
                        if (data.sucflag) {
                            $scope.info = {
                                show: true,
                                msg: '系统用户更新成功'
                            }
                            $location.path('/basicuserment');
                        }
                    }).error(function(data, status, headers, config) {
                        $scope.errors = {
                            show: true,
                            msg: '系统异常'
                        }
                    });
                }
            }
        }

    }


    //设置系统用户权限
    basicusermodule.controller('basicuserrole',serverUserRole);
    function serverUserRole($stateParams,$state,$scope,$http,$location) {

        var operate = $location.search().operate || $stateParams.operate;
        if (operate != undefined && operate == "edit") {
            $scope.basicuserid=$location.search().id;
            //获取系统用户的角色信息
            $scope.title="编辑系统用户角色信息";
            //获取所有系统角色信息
            $http({
                method: 'POST',
                url: '../mall/sysrole/findAll'
            }).success(function (data, status, headers, config) {
                if (data.sucflag) {
                    $scope.gtparams = data.beanlist;
                    $scope.updatebtn = {show: true};
                }
            }).error(function (data, status, headers, config) {
                $scope.errors = {
                    show: true,
                    msg: '系统异常'
                }
            });


            //获取用户角色拥有的权限信息
            $http({
                method: 'POST',
                url: '../mall/basicuserrole/find',
                data:{
                    'basicuserid':$scope.basicuserid
                }
            }).success(function (data, status, headers, config) {
                if (data.sucflag) {
                    if(data.bean!=null&&data.bean!=undefined){
                        $scope.username=data.bean.username;
                        $scope.basicuserid=data.bean.id;
                    }
                    angular.forEach(data.beanlist,function(d,i,a){
                        $scope.selected.push(d.id);
                    });
                }
            }).error(function (data, status, headers, config) {
                $scope.errors = {
                    show: true,
                    msg: '系统异常'
                }
            });


            //更新用户角色信息var idstrs=ids.join(",");
            $scope.update=function(){
                var sysroleid=$scope.selected.join(",");
                $http({
                    method: 'POST',
                    url: '../mall/basicuserrole/update',
                    data:{
                        'basicuserid': $scope.basicuserid,
                        'sysroleid':sysroleid
                    }
                }).success(function (data, status, headers, config) {
                    if (data.sucflag) {
                        $scope.errors={};
                        $scope.info={
                            show:true,
                            msg:'系统用户权限更新成功'
                        }
                        $location.path('/basicuserment');
                    }else{
                        $scope.errors = {
                            show: true,
                            msg: data.msg
                        }
                    }
                }).error(function (data, status, headers, config) {
                    $scope.errors = {
                        show: true,
                        msg: '系统异常'
                    }
                });
            }


            //角色选择控制
            $scope.selected=[];

            var updateSelected=function(action,id){
                if(action=='add'&&$scope.selected.indexOf(id)==-1){
                    $scope.selected.push(id);
                }
                if(action=='remove'&&$scope.selected.indexOf(id)!=-1){
                    var idx=$scope.selected.indexOf(id);
                    $scope.selected.splice(idx,1);
                }
            }

            $scope.updateSelection=function($event,id){
                var checkbox=$event.target;
                var action=(checkbox.checked?'add':'remove');
                updateSelected(action,id);
            }
            $scope.isSelected=function(id){
                return $scope.selected.indexOf(id)>=0;
            }

        }
    }


    //系统用户列表
    basicusermodule.controller('basicuserment', serverBasicusermentCtrl);
    //查询列表数据
    function serverBasicusermentCtrl($http,$location,$compile,$scope,$rootScope,$resource,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer){
    $scope.title="系统用户列表";
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/basicuser/findByPage',
			dataSrc:'data'
		})
		.withOption('processing',true)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
            if (!$scope.headerCompiled) {
                $scope.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
        .withOption('stateSave', true)
        .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json')

		$scope.$on('handleRequest',function(){

		});

		vm.dtColumns=[
		              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
		            	  vm.selected[full.id]=false;
		            	  return '<input type="checkbox" ng-model="showCase.selected['+data.id+']" ng-click="showCase.toggleOne(showCase.selected)">';
		              }),
		              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
		      		  DTColumnBuilder.newColumn('username').withTitle('用户名').notSortable(),
            DTColumnBuilder.newColumn('mobile').withTitle('手机号').notSortable(),
            DTColumnBuilder.newColumn('sysrole').withTitle('用户角色').notSortable(),
            DTColumnBuilder.newColumn('userstatus').withTitle('用户状态').notSortable(),
            DTColumnBuilder.newColumn('registertime').withTitle('注册时间').notSortable(),
            DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
		      		  DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
		      		  DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
		      		  DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)];
		function actionHtml(data,type,full,meta){
            return "<button class='btn btn-warning' ng-click=\"edit('"+data.id+"')\"><i class='fa fa-edit'></i></button>"+
                "<button sytle='margin-left:10px' class='btn btn-success' ng-click=\"setbasicuserrole('"+data.id+"')\">权限设置</button>";
        }

		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}

        /**
         * 复杂搜索刷新数据
         */
        function searchReloadData(){
            var resetPaging=false;
            var searchParams={
                isCustomSearch:1,
                name:''
            };
            if($scope.name!=undefined){
                searchParams.name=$scope.name;
                vm.dtOptions['ajax'].data=searchParams;
                vm.dtInstance.reloadData(callback, resetPaging);
            }
        }

        /**
         * 表格
         */
        $scope.searchdataTableCustom=function(){
            searchReloadData();
        }

        //设置系统用户角色
        $scope.setbasicuserrole=function(id){
            $location.path('/basicuserrole').search({'operate':'edit','id':id});

        }
		//表格中编辑按钮
		$scope.edit=function(id,name){
			$location.path('/basicuser').search({'operate':'edit','id':id});
		}


		$scope.save=function(){
			$location.path('/basicuser').search({'operate':'save'});
		}

		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/basicuser/del',
					data:{
						'id':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'批量删除成功'
						}
						reloadData();
					}

				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}
	}

});
